﻿using System;
using System.Collections.Generic;
using System.Text;
using FlexminAPI;
using System.Diagnostics;
using System.Threading;
using System.IO;

namespace FlexConsole
{
	public class ConSlave : ISlave
	{
		public string CmdOutputBuffer;

		private Process CmdProc;

		public bool StartProcessThread()
		{
			try
			{
				// Создаем новый поток и в нем буим пускать cmd.exe
				CmdProc = new Process();
				ProcessStartInfo CmdStartInfo = new ProcessStartInfo("cmd.exe");
				CmdStartInfo.StandardOutputEncoding = Encoding.GetEncoding("CP866");
				CmdStartInfo.CreateNoWindow = true;
				CmdStartInfo.UseShellExecute = false;
				CmdStartInfo.RedirectStandardOutput = true;
				CmdStartInfo.RedirectStandardError = true;
				CmdStartInfo.RedirectStandardInput = true;
				CmdProc.StartInfo = CmdStartInfo;
				return CmdProc.Start();
			}
			catch
			{
				return false;
			}
		}

		public void StopProcessThread()
		{
			CmdProc.Kill();
		}

		public string ConsoleRead()
		{
			try
			{
				char[] output = new char[4096];
				CmdProc.StandardOutput.Read(output, 0, output.Length);
				return new string(output);
			}
			catch (IOException)
			{
				return "Input/Output error occured!\n";
			}
		}

		public string ConsoleErrorRead()
		{
			try
			{
				char[] errors = new char[4096];
				CmdProc.StandardError.Read(errors, 0, errors.Length);
				return new string(errors);
			}
			catch (IOException)
			{
				return "Input/Output error occured!\n";
			}
		}

		public void Exec(string cmd)
		{
			try
			{
				CmdProc.StandardInput.Write(cmd);				
			}
			catch
			{
				//TODO: Proper error handling.
			}
		}
		
	}
}
